package com.yh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.model.Product;
import com.yh.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    ProductService productService;

    @RolesAllowed({"ADMIN","GroupManger"})
    @GetMapping("findAll")
    public String findAll(@RequestParam(value = "page",defaultValue = "1") Integer page,
                          @RequestParam(value = "size",defaultValue = "5") Integer size,
                          Model model){
        PageHelper.startPage(page,size);
        List<Product> productList = productService.findAll();
        PageInfo pageInfo = new PageInfo(productList);

        model.addAttribute("pageInfo",pageInfo);
        return "product-list"; //相当于product-list.html
    }

    @PostMapping("save")
    public String save(Product product){
        productService.save(product);
        return "redirect:findAll";
    }

    //修改之前的数据回显
    //product/editById?id=25
    @RequestMapping("editById")
    public String editById(@RequestParam("id") Integer id,Model model){
        Product product = productService.findById(id);
        model.addAttribute("product",product);
        return "product-edit";
    }

    //修改操作 edit
    @RequestMapping("edit")
    public String edit(Product product){
        productService.edit(product);
        return "redirect:findAll";
    }

    //    详情
    //    /product/findById?id=25
    @RequestMapping("findById")
    public String findById(@RequestParam("id") Integer id,Model model){
        Product product = productService.findById(id);
        model.addAttribute("product",product);
        return "product-show";
    }


    // /deleteById?id=25
    @RequestMapping("deleteById")
    public String deleteById(@RequestParam("id") Integer id){
        productService.deleteById(id);
        return "redirect:findAll";
    }

    //批量删除
    //product/selectDelete
    @RequestMapping("selectDelete")
    public String selectDelete(@RequestParam("ids") Integer[] ids){
        productService.selectDelete(ids);
        return "redirect:findAll";
    }
}
